package com.party.web.biz.distribution;

import com.google.common.base.Function;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.distributor.*;
import com.party.core.model.member.Member;
import com.party.core.model.member.MemberGroup;
import com.party.core.service.distributor.IDistributorCountService;
import com.party.core.service.distributor.IDistributorDetailService;
import com.party.core.service.distributor.IDistributorRelationService;
import com.party.core.service.distributor.IDistributorTargetAttacheService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.IMemberService;
import com.party.web.utils.RealmUtils;
import com.party.web.web.dto.input.common.CommonQuery;
import com.party.web.web.dto.input.distribution.ChildListInput;
import com.party.web.web.dto.input.distribution.DistributionListInput;
import com.party.web.web.dto.output.distribution.ChildListOutput;
import com.party.web.web.dto.output.distribution.DistributionListOutput;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.function.Consumer;

/**
 * 分销业务接口
 * Created by wei.li
 *
 * @date 2017/3/13 0013
 * @time 10:56
 */

@Service
public class DistributionBizService {

    @Autowired
    private IDistributorRelationService distributorRelationService;

    @Autowired
    private IMemberGroupService memberGroupService;
    @Autowired
    private IMemberService memberService;

    @Autowired
    private IDistributorCountService distributorCountService;
    @Autowired
    private IDistributorDetailService distributorDetailService;
    @Autowired
    private IDistributorTargetAttacheService distributorTargetAttacheService;


    /**
     * 我分销的列表
     * @param distributionListInput 分销关系
     * @param page 分页参数
     * @return 分销列表
     */
    public List<DistributionListOutput> list(DistributionListInput distributionListInput, Page page){
        MemberGroup member = RealmUtils.getCurrentUser();


        List<WithCount> withCountList = distributorRelationService.listWithCount(distributionListInput.getTitle(),
                distributionListInput.getType(), member.getId(), null, null,  page);

        List<DistributionListOutput> listOutputs = LangUtils.transform(withCountList, new Function<WithCount, DistributionListOutput>() {
            @Override
            public DistributionListOutput apply(WithCount withCount) {
                DistributionListOutput distributionListOutput = DistributionListOutput.transform(withCount);
                MemberGroup member = memberGroupService.get(withCount.getParentId());
                distributionListOutput.setParentName(member.getRealname());
                return distributionListOutput;
            }
        });
        return listOutputs;
    }

    /**
     * 根据目标查询分销关系
     * @param targetId 目标编号
     * @param input 输入视图
     * @param page 分页参数
     * @return 分销列表
     */
    public List<DistributionListOutput> targetList(String targetId, DistributionListInput input, Page page){

        String startTime = input.getStartDate();
        String endTime = input.getEndDate();
        if (null != input.getTimeType() && !new Integer(0).equals(input.getTimeType())) {
            CommonQuery commonQuery = new CommonQuery();
            commonQuery.setTimeType(input.getTimeType());
            startTime = commonQuery.getCreateStart();
            endTime = commonQuery.getCreateEnd();
        }

        List<WithCount> withCountList
                = distributorRelationService.listWithCount(targetId, input.getTitle(),
                input.getType(), startTime, endTime,  page);

        List<DistributionListOutput> listOutputs = LangUtils.transform(withCountList, new Function<WithCount, DistributionListOutput>() {
            @Override
            public DistributionListOutput apply(WithCount withCount) {
                DistributionListOutput distributionListOutput = DistributionListOutput.transform(withCount);
                MemberGroup member = memberGroupService.get(withCount.getParentId());
                distributionListOutput.setParentName(member.getRealname());

                Member distributor = memberService.get(withCount.getDistributorId());
                distributionListOutput.setDistributorName(distributor.getRealname());
                distributionListOutput.setDistributorLogo(distributor.getLogo());
                return distributionListOutput;
            }
        });
        return listOutputs;
    }


    /**
     * 子级分销列表
     * @param distributionId 分销编号
     * @param input 输入视图
     * @param page 分页参数
     * @return 子级分销列表
     */
    public List<ChildListOutput> childList(String distributionId, ChildListInput input, Page page){

        String startTime = input.getStartDate();
        String endTime = input.getEndDate();
        if (null != input.getTimeType() && !new Integer(0).equals(input.getTimeType())) {
            CommonQuery commonQuery = new CommonQuery();
            commonQuery.setTimeType(input.getTimeType());
            startTime = commonQuery.getCreateStart();
            endTime = commonQuery.getCreateEnd();
        }

        //查询本级分销信息
        DistributorRelation distributorRelation = distributorRelationService.get(distributionId);

        //下级分销商
        List<WithCount> list = distributorRelationService.findByParentId(distributorRelation.getDistributorId(),
                distributorRelation.getTargetId(), input.getTitle(), input.getDistributorName(), input.getType(), startTime, endTime, page);
        List<ChildListOutput> childList = LangUtils.transform(list, new Function<WithCount, ChildListOutput>() {
            @Override
            public ChildListOutput apply(WithCount withCount) {
                ChildListOutput childListOutput = ChildListOutput.transform(withCount);
                Member member = memberService.get(withCount.getDistributorId());
                childListOutput.setDistributorName(member.getRealname());
                childListOutput.setDistributorLogo(member.getLogo());
                return childListOutput;
            }
        });
        return childList;
    }

    /**
     * 删除分销关系
     *
     * @param targetId      目标编号
     * @param distributorId 分销者编号
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void deleteDistributionBiz(String targetId, String distributorId) {
        List<DistributorRelation> distributorRelations = distributorRelationService.findByTargetId(targetId, distributorId);
        distributorRelations.forEach(new Consumer<DistributorRelation>() {
            @Override
            public void accept(DistributorRelation distributorRelation) {
                distributorCountService.deleteByRelationId(distributorRelation.getId());
                distributorDetailService.deleteByRelationId(distributorRelation.getId());
                distributorTargetAttacheService.deleteByRelationId(distributorRelation.getId());
                distributorRelationService.delete(distributorRelation.getId());
            }
        });
    }
    /**
     * 统计数据
     * @param distributorRelationId 分销关系编号
     * @param type 类型
     */

    @Transactional
    public  void distributorCount(String distributorRelationId, Integer type){
        DistributorCount distributorCount = distributorCountService.findByRelationIdLock(distributorRelationId);
        if (null == distributorCount){
            throw new BusinessException("分销统计不存在");
        }

        List<DistributorDetail> distributorDetails = distributorDetailService
                .findByRelationId(distributorRelationId, type);
        if (DistributorDetailType.DISTRIBUTOR_TYPE_APPLY.getCode().equals(type)) {
            distributorCount.setApplyNum(distributorDetails.size());
        }
        else if (DistributorDetailType.DISTRIBUTOR_TYPE_ORDER.getCode().equals(type)){
            distributorCount.setSalesNum(distributorDetails.size());
        }
        else if (DistributorDetailType.DISTRIBUTOR_TYPE_CROWDFUN.getCode().equals(type)){

            distributorCount.setCrowdfundNum(distributorDetails.size());
        }
        else if (DistributorDetailType.DISTRIBUTOR_TYPE_SUPPORT.getCode().equals(type)){
            distributorCount.setFavorerNum(distributorDetails.size());
        }
        else {
            throw new BusinessException("分销详情类型错误");
        }
        distributorCountService.update(distributorCount);
    }
}
